// 粒子系统 - 替代图片的粒子效果
class ParticleImageSystem {
    constructor() {
        this.canvasCache = new Map();
        this.particleConfigs = this.createParticleConfigs();
        this.initStyles();
    }

    // 创建不同场景的粒子配置
    createParticleConfigs() {
        return {
            // 实验室场景
            'lab_night': {
                colors: ['#00d4ff', '#4ecdc4', '#ffffff'],
                particleCount: 150,
                pattern: 'laboratory',
                speed: 0.5,
                size: { min: 1, max: 3 }
            },
            'data_screen': {
                colors: ['#00ff00', '#00cc00', '#ffffff'],
                particleCount: 200,
                pattern: 'matrix',
                speed: 1.2,
                size: { min: 1, max: 2 }
            },
            'blue_glow': {
                colors: ['#0099ff', '#66ccff', '#99ddff'],
                particleCount: 180,
                pattern: 'glow',
                speed: 0.8,
                size: { min: 2, max: 4 }
            },
            'emergency_shutdown': {
                colors: ['#ff4444', '#ff6666', '#ffffff'],
                particleCount: 120,
                pattern: 'alert',
                speed: 1.5,
                size: { min: 1, max: 3 }
            },
            'scientific_discovery': {
                colors: ['#ffd700', '#ffec8c', '#ffffff'],
                particleCount: 160,
                pattern: 'discovery',
                speed: 0.6,
                size: { min: 1, max: 4 }
            },

            // 第2章场景
            'morning_lab': {
                colors: ['#ffaa00', '#ff8800', '#ffffff'],
                particleCount: 140,
                pattern: 'morning',
                speed: 0.4,
                size: { min: 1, max: 3 }
            },
            'time_agent': {
                colors: ['#8844ff', '#aa66ff', '#ffffff'],
                particleCount: 160,
                pattern: 'temporal',
                speed: 1.0,
                size: { min: 1, max: 3 }
            },
            'sarah_discussion': {
                colors: ['#ff6b6b', '#ff8e8e', '#ffffff'],
                particleCount: 100,
                pattern: 'conversation',
                speed: 0.3,
                size: { min: 1, max: 2 }
            },

            // 第3章场景  
            'multiverse_portal': {
                colors: ['#ff00ff', '#00ffff', '#ffff00'],
                particleCount: 250,
                pattern: 'portal',
                speed: 2.0,
                size: { min: 2, max: 5 }
            },
            'tech_world': {
                colors: ['#00ffff', '#0099cc', '#ffffff'],
                particleCount: 180,
                pattern: 'technology',
                speed: 1.5,
                size: { min: 1, max: 3 }
            },
            'magic_world': {
                colors: ['#ff6600', '#ff9933', '#ffcc66'],
                particleCount: 200,
                pattern: 'magic',
                speed: 0.8,
                size: { min: 2, max: 4 }
            },

            // 第4章场景
            'cosmic_choice': {
                colors: ['#6600ff', '#9933ff', '#cc66ff'],
                particleCount: 220,
                pattern: 'cosmic',
                speed: 1.2,
                size: { min: 2, max: 5 }
            },
            'guardian_oath': {
                colors: ['#gold', '#ffcc00', '#ffffff'],
                particleCount: 180,
                pattern: 'guardian',
                speed: 0.6,
                size: { min: 1, max: 4 }
            },

            // 第5章结局
            'eternal_echo': {
                colors: ['#ff0099', '#ff33aa', '#ff66bb'],
                particleCount: 300,
                pattern: 'eternal',
                speed: 0.5,
                size: { min: 2, max: 6 }
            },

            // 默认配置
            'default': {
                colors: ['#00d4ff', '#4ecdc4', '#ffffff'],
                particleCount: 150,
                pattern: 'default',
                speed: 1.0,
                size: { min: 1, max: 3 }
            }
        };
    }

    // 初始化样式
    initStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .particle-canvas {
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 8px;
                background: linear-gradient(135deg, #0a0e1a 0%, #1a1f2e 50%, #2a2f3e 100%);
                animation: particleGlow 3s ease-in-out infinite alternate;
            }
            
            @keyframes particleGlow {
                0% { filter: brightness(1.0) contrast(1.0); }
                100% { filter: brightness(1.2) contrast(1.1); }
            }
            
            .scene-img-container {
                position: relative;
                overflow: hidden;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            }
            
            .particle-overlay {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                pointer-events: none;
                z-index: 1;
            }
        `;
        document.head.appendChild(style);
    }

    // 获取场景名称（从图片路径中提取）
    getSceneName(imagePath) {
        if (!imagePath) return 'default';
        const match = imagePath.match(/images\/([^.]+)/);
        return match ? match[1] : 'default';
    }

    // 创建粒子画布
    createParticleCanvas(imagePath, width = 600, height = 400) {
        const sceneName = this.getSceneName(imagePath);
        const cacheKey = `${sceneName}_${width}_${height}`;
        
        // 检查缓存
        if (this.canvasCache.has(cacheKey)) {
            return this.canvasCache.get(cacheKey).cloneNode(true);
        }

        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        canvas.className = 'particle-canvas';
        
        const ctx = canvas.getContext('2d');
        const config = this.particleConfigs[sceneName] || this.particleConfigs.default;
        
        this.drawParticleScene(ctx, config, width, height);
        
        // 缓存画布
        this.canvasCache.set(cacheKey, canvas);
        
        return canvas.cloneNode(true);
    }

    // 绘制粒子场景
    drawParticleScene(ctx, config, width, height) {
        // 清空画布
        ctx.fillStyle = 'rgba(10, 14, 26, 1)';
        ctx.fillRect(0, 0, width, height);

        // 根据场景模式绘制不同的粒子效果
        switch (config.pattern) {
            case 'laboratory':
                this.drawLaboratoryPattern(ctx, config, width, height);
                break;
            case 'matrix':
                this.drawMatrixPattern(ctx, config, width, height);
                break;
            case 'glow':
                this.drawGlowPattern(ctx, config, width, height);
                break;
            case 'portal':
                this.drawPortalPattern(ctx, config, width, height);
                break;
            case 'cosmic':
                this.drawCosmicPattern(ctx, config, width, height);
                break;
            case 'magic':
                this.drawMagicPattern(ctx, config, width, height);
                break;
            default:
                this.drawDefaultPattern(ctx, config, width, height);
        }

        // 添加场景标识文字
        this.drawSceneLabel(ctx, config, width, height);
    }

    // 实验室模式
    drawLaboratoryPattern(ctx, config, width, height) {
        // 绘制网格背景
        ctx.strokeStyle = 'rgba(0, 212, 255, 0.3)';
        ctx.lineWidth = 1;
        
        for (let x = 0; x < width; x += 40) {
            ctx.beginPath();
            ctx.moveTo(x, 0);
            ctx.lineTo(x, height);
            ctx.stroke();
        }
        
        for (let y = 0; y < height; y += 40) {
            ctx.beginPath();
            ctx.moveTo(0, y);
            ctx.lineTo(width, y);
            ctx.stroke();
        }

        // 绘制粒子
        for (let i = 0; i < config.particleCount; i++) {
            const x = Math.random() * width;
            const y = Math.random() * height;
            const size = Math.random() * (config.size.max - config.size.min) + config.size.min;
            const color = config.colors[Math.floor(Math.random() * config.colors.length)];
            
            ctx.fillStyle = color;
            ctx.globalAlpha = Math.random() * 0.8 + 0.2;
            ctx.beginPath();
            ctx.arc(x, y, size, 0, Math.PI * 2);
            ctx.fill();
        }
    }

    // 矩阵模式
    drawMatrixPattern(ctx, config, width, height) {
        // 绘制数字雨效果
        ctx.font = '12px monospace';
        ctx.fillStyle = config.colors[0];
        
        for (let i = 0; i < 50; i++) {
            const x = Math.random() * width;
            const y = Math.random() * height;
            const char = String.fromCharCode(48 + Math.floor(Math.random() * 10)); // 0-9
            ctx.globalAlpha = Math.random() * 0.6 + 0.2;
            ctx.fillText(char, x, y);
        }

        // 添加粒子
        this.drawDefaultPattern(ctx, config, width, height);
    }

    // 光芒模式
    drawGlowPattern(ctx, config, width, height) {
        // 创建径向渐变
        const centerX = width / 2;
        const centerY = height / 2;
        const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, Math.max(width, height) / 2);
        
        gradient.addColorStop(0, 'rgba(0, 153, 255, 0.8)');
        gradient.addColorStop(0.5, 'rgba(102, 204, 255, 0.4)');
        gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
        
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, width, height);

        // 添加光粒子
        for (let i = 0; i < config.particleCount; i++) {
            const angle = Math.random() * Math.PI * 2;
            const distance = Math.random() * Math.min(width, height) / 2;
            const x = centerX + Math.cos(angle) * distance;
            const y = centerY + Math.sin(angle) * distance;
            const size = Math.random() * (config.size.max - config.size.min) + config.size.min;
            
            ctx.fillStyle = config.colors[Math.floor(Math.random() * config.colors.length)];
            ctx.globalAlpha = Math.random() * 0.8 + 0.2;
            ctx.beginPath();
            ctx.arc(x, y, size, 0, Math.PI * 2);
            ctx.fill();
        }
    }

    // 传送门模式
    drawPortalPattern(ctx, config, width, height) {
        const centerX = width / 2;
        const centerY = height / 2;
        
        // 绘制螺旋效果
        for (let i = 0; i < config.particleCount; i++) {
            const angle = i * 0.1;
            const radius = (i / config.particleCount) * Math.min(width, height) / 2;
            const x = centerX + Math.cos(angle) * radius;
            const y = centerY + Math.sin(angle) * radius;
            const size = Math.random() * (config.size.max - config.size.min) + config.size.min;
            
            ctx.fillStyle = config.colors[i % config.colors.length];
            ctx.globalAlpha = 1 - (i / config.particleCount);
            ctx.beginPath();
            ctx.arc(x, y, size, 0, Math.PI * 2);
            ctx.fill();
        }
    }

    // 宇宙模式
    drawCosmicPattern(ctx, config, width, height) {
        // 绘制星空背景
        for (let i = 0; i < config.particleCount; i++) {
            const x = Math.random() * width;
            const y = Math.random() * height;
            const size = Math.random() * (config.size.max - config.size.min) + config.size.min;
            const color = config.colors[Math.floor(Math.random() * config.colors.length)];
            
            ctx.fillStyle = color;
            ctx.globalAlpha = Math.random() * 0.9 + 0.1;
            
            // 绘制星星效果
            ctx.beginPath();
            ctx.arc(x, y, size, 0, Math.PI * 2);
            ctx.fill();
            
            // 添加十字光芒
            if (Math.random() > 0.8) {
                ctx.strokeStyle = color;
                ctx.lineWidth = 1;
                ctx.globalAlpha = 0.5;
                ctx.beginPath();
                ctx.moveTo(x - size * 2, y);
                ctx.lineTo(x + size * 2, y);
                ctx.moveTo(x, y - size * 2);
                ctx.lineTo(x, y + size * 2);
                ctx.stroke();
            }
        }
    }

    // 魔法模式
    drawMagicPattern(ctx, config, width, height) {
        // 绘制魔法光环
        for (let i = 0; i < 5; i++) {
            const centerX = Math.random() * width;
            const centerY = Math.random() * height;
            const radius = Math.random() * 50 + 20;
            
            const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
            gradient.addColorStop(0, config.colors[0] + '80');
            gradient.addColorStop(1, config.colors[0] + '00');
            
            ctx.fillStyle = gradient;
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
            ctx.fill();
        }

        // 添加魔法粒子
        this.drawDefaultPattern(ctx, config, width, height);
    }

    // 默认模式
    drawDefaultPattern(ctx, config, width, height) {
        for (let i = 0; i < config.particleCount; i++) {
            const x = Math.random() * width;
            const y = Math.random() * height;
            const size = Math.random() * (config.size.max - config.size.min) + config.size.min;
            const color = config.colors[Math.floor(Math.random() * config.colors.length)];
            
            ctx.fillStyle = color;
            ctx.globalAlpha = Math.random() * 0.8 + 0.2;
            ctx.beginPath();
            ctx.arc(x, y, size, 0, Math.PI * 2);
            ctx.fill();
        }
    }

    // 绘制场景标识
    drawSceneLabel(ctx, config, width, height) {
        ctx.globalAlpha = 0.6;
        ctx.fillStyle = '#ffffff';
        ctx.font = 'bold 16px "Microsoft YaHei", sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('时空回音', width / 2, height - 20);
        
        ctx.font = '12px "Microsoft YaHei", sans-serif';
        ctx.fillStyle = '#cccccc';
        ctx.fillText('Time Echo', width / 2, height - 5);
    }

    // 替换所有图片元素
    replaceAllImages() {
        console.log('🎨 开始将所有图片替换为粒子效果...');
        
        // 替换现有的img元素
        const images = document.querySelectorAll('img[src*="images/"]');
        images.forEach(img => {
            this.replaceImageWithParticles(img);
        });

        // 监听新添加的图片
        this.observeNewImages();
        
        console.log(`✅ 已替换 ${images.length} 个图片元素为粒子效果`);
    }

    // 替换单个图片
    replaceImageWithParticles(img) {
        const rect = img.getBoundingClientRect();
        const width = Math.max(rect.width || 600, 300);
        const height = Math.max(rect.height || 400, 200);
        
        const canvas = this.createParticleCanvas(img.src, width, height);
        
        // 复制img的属性到canvas
        canvas.className = img.className + ' particle-canvas';
        canvas.style.cssText = img.style.cssText;
        
        // 替换元素
        img.parentNode.replaceChild(canvas, img);
    }

    // 监听新图片的添加
    observeNewImages() {
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) { // Element node
                        // 检查新添加的img元素
                        if (node.tagName === 'IMG' && node.src && node.src.includes('images/')) {
                            setTimeout(() => this.replaceImageWithParticles(node), 100);
                        }
                        
                        // 检查子元素中的img
                        const imgs = node.querySelectorAll && node.querySelectorAll('img[src*="images/"]');
                        if (imgs) {
                            imgs.forEach(img => {
                                setTimeout(() => this.replaceImageWithParticles(img), 100);
                            });
                        }
                    }
                });
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }
}

// 创建全局粒子系统实例
window.particleImageSystem = new ParticleImageSystem();

// 页面加载完成后自动替换所有图片
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        setTimeout(() => window.particleImageSystem.replaceAllImages(), 500);
    });
} else {
    setTimeout(() => window.particleImageSystem.replaceAllImages(), 500);
}

console.log('🎆 粒子图片系统已初始化');